<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

require_once  __DIR__ . '/includes/authenticate.php';

include_once __DIR__ . '/db_bb_connect.php';

include __DIR__ . '/mainpage.php';


$edit_ID = $_POST['ID'];

//$edit_ID = '24';

$sql = "SELECT * FROM video_feedback WHERE ID = '$edit_ID'";

$result = $db->query($sql);

$row = $result->fetch_assoc();

$season = $row['season'];
$gamenumber = $row['gamenumber'];

$title = $row['title'];
$text = $row['comment'];
$time_start = $row['time_start'];
$time_end = $row['time_end'];
$type = $row['type'];


$tags_selected = $row['action_tags'];
$players_selected = $row['players'];  


?>

<div id="tagging">

<div class="container-fluid">
<div class="row">
<div class="col-lg-3 col-md-3"></div>
<div class="col-lg-6 col-md-6"> 

  <h3 align="center">Edit Video Feedback Entry</h3>


 </div>
<div class="col-lg-3 col-md-3"></div>
</div>
</div>

<?php

/// GET YOUTUBE EMBED CODE ///

$sql = "SELECT embed_code, opponent FROM games WHERE season = '$season' AND gamenumber = '$gamenumber'";

$result = $db->query($sql);
$row = $result->fetch_assoc();
$youtubeID = $row['embed_code'];
$opponent_teamname = $row['opponent'];

/// CREATE PLAYERS LIST ///

$sql = "SELECT users.user_key, users.firstname, users.type, users.lastname, teams.playernumber
FROM users 
JOIN teams
ON users.user_key = teams.playerID
WHERE (users.type = 'Player' OR users.type = 'Team') 
AND teams.season = '$season'
ORDER BY teams.playernumber";

$result = $db->query($sql);

$players = "";

while( $row = $result->fetch_assoc()){ 

  $user_key = $row['user_key']; 
  $lastname = $row['lastname']; 
  $firstname = $row['firstname']; 
  $playernumber = $row['playernumber'];

  $players .= "{ value: \"$user_key\", label: \"$playernumber $firstname $lastname\" },";

  }

  /// ADD OPPONENT PLAYERS LIST ///

$sql = "SELECT teamID FROM teams_list WHERE teamname = '$opponent_teamname'";

$result = $db->query($sql);
$row = $result->fetch_assoc();

$opponent_teamID = $row['teamID']; 

$sql = "SELECT users.user_key, users.firstname, users.type, users.lastname, teams_opponents.playernumber
FROM users 
JOIN teams_opponents
ON users.user_key = teams_opponents.playerID
WHERE 
(users.type = 'Player' OR users.type = 'Team')  
AND teams_opponents.season = '$season'
AND teams_opponents.teamID = '$opponent_teamID'
ORDER BY teams_opponents.playernumber";

$result = $db->query($sql);

while( $row = $result->fetch_assoc()){ 

  $user_key = $row['user_key']; 
  $lastname = $row['lastname']; 
  $firstname = $row['firstname']; 
  $playernumber = $row['playernumber'];

  $players .= "{ value: \"$user_key\", label: \"$playernumber $firstname $lastname\" },";

  }

/// CREATE TAGS LIST ///

$tags = ""; 

$sql = "SELECT tag, ID FROM video_feedback_taglist";

$result = $db->query($sql);

while( $row = $result->fetch_assoc()){ 
      $tag = $row['tag'];
      $ID = $row['ID'];

      $tags .= "{ value: \"$ID\", label: \"$tag\" },";
}

  
?>

  <div class="container">
    <div class="row">
     <div align="center" class="col-md-8" style="margin:0 auto; float:none;">
          <h3> Season <?= $season; ?> Game <?= $gamenumber; ?></h3>
      <div id="player"></div>
     </div>
   </div>
   <div class="row">
     <br />
     <div class="col-md-6" style="margin:0 auto; float:none;">
      
      <form method="post" id="programmer_form">
        <input type="hidden" name="ID" value="<?= $edit_ID ?>">
          <div class="row">
            <div class="form-group">
              <div class="col-md-6">
                  <label>Time Start</label>   <button class="btn btn-sm btn-default timestart">Get Current Time</button>               
                  <input type="number" name="timestart" id="timestart" class="form-control" placeholder="Time Start" value="<?= $time_start ?>" />
                </div>
                <div class="col-md-6">
                  <label>Time End</label>
                  <button class="btn btn-sm btn-default timeend">Get Current Time</button>
                  <input type="number" name="timeend" id="timeend" class="form-control" placeholder="Time End" value="<?= $time_end ?>" />
               </div>
             </div>
          </div>
                    <br>
        <input type="hidden" name="type" value="feedback" >

          <div class="form-group">
        <label>Title</label>
        <input type="text" name="title" id="title" class="form-control" value="<?=$title?>">
       </div>

        <div class="form-group">
        <label>Comment</label>
        <textarea type="text" name="comment" id="comment" class="form-control" rows="5"><?= $text ?></textarea>
       </div>
       <div class="form-group tags">
        <label>Action Tags</label>
        <input type="text" name="tags" id="tags" class="form-control" placeholder="Choose your tags..." />
       </div>
        <div class="form-group players">
        <label>Players Involved</label>
         <input type="text" name="players" id="players" class="form-control" placeholder="Choose your players..." />
       </div>
       <span id="success_message"></span>
       <div class="form-group">
        <input type="submit" name="submit" id="submit" class="btn btn-lg btn-block btn-success" value="Update" />
       </div>
      </form>
      
      </div>
     </div>
    </div>
<script>
$(document).ready(function(){
 
 $('#tags').tokenfield({
  autocomplete:{
   source: [<?= $tags; ?>],
   delay:100
  },
  showAutocompleteOnFocus: true
 });

  $('#players').tokenfield({
  autocomplete:{
   source: [<?= $players; ?>],
   delay:100
  },
  showAutocompleteOnFocus: true
 });

 $('#programmer_form').on('submit', function(event){
  event.preventDefault();
  if($.trim($('#timestart').val()).length == 0)
  {
   alert("Please Enter a Time Start");
   return false;
  }
  else if($.trim($('#timeend').val()).length == 0)
  {
   alert("Please Enter a Time End");
   return false;
  }
  else if($.trim($('#tags').val()).length == 0)
  {
   alert("Please Enter At least One Action Tag");
   return false;
  }
  else if($.trim($('#players').val()).length == 0)
  {
   alert("Please Enter At least One Player");
   return false;
  }
  else
  {
   var form_data = $(this).serialize();
   $('#submit').attr("disabled","disabled")
   
   $.ajax({
    url: "./includes/handlers/video_feedback_edit_entry_handler.php",
    method: "POST",
    data: form_data,
    beforeSend:function(){
     $('#submit').val('Updating...');
     },
    success:function(data){
    if(data != '')
     {
      $('#success_message').html(data);
      $('#submit').attr("disabled", false);
      $('#submit').val('Update');
     }    
    }, 
    error: function (xhr, status, error) {
          alert(xhr.responseText); 
    }
   });
   setInterval(function(){
    $('#success_message').html('');
   }, 5000);
  }
  });

<?php

$tags_selected_explode = explode(',', $tags_selected);

foreach ($tags_selected_explode as $tagID) {

$sql = "SELECT tag FROM video_feedback_taglist WHERE ID = '$tagID'";

$result = $db->query($sql);
$row = $result->fetch_assoc();
$tagname = $row['tag'];

  echo "$('#tags').tokenfield('createToken', { value: '$tagID', label: '$tagname' });";
}


$players_selected_explode = explode(',', $players_selected);

foreach ($players_selected_explode as $selected_user_key) {

  $sql = "SELECT users.user_key, users.firstname, users.type, users.lastname, teams_opponents.playernumber
  FROM users 
  JOIN teams_opponents
  ON users.user_key = teams_opponents.playerID
  WHERE (users.type = 'Player' OR users.type = 'Team')  
  AND teams_opponents.season = '$season'
  AND teams_opponents.teamID = '$opponent_teamID'
  AND teams_opponents.playerID = '$selected_user_key'";

  $result = $db->query($sql);

  $row = $result->fetch_assoc();

  $user_key = $row['user_key']; 
  $lastname = addslashes($row['lastname']); 
  $firstname = addslashes($row['firstname']); 
  $playernumber = $row['playernumber'];

  if( mysqli_num_rows($result) != 0) { echo "$('#players').tokenfield('createToken', { value: '$user_key', label: '$playernumber $firstname $lastname' });";}

}

foreach ($players_selected_explode as $selected_user_key) {

  $sql = "SELECT users.firstname, users.lastname, teams.playernumber, users.type, users.user_key
  FROM users 
  JOIN teams
  ON users.user_key = teams.playerID
  WHERE (users.type = 'Player' OR users.type = 'Team') 
  AND teams.season = '$season'
  AND users.user_key = '$selected_user_key'";

  $result = $db->query($sql);

  $row = $result->fetch_assoc();

  $user_key = $row['user_key']; 
  $lastname = addslashes($row['lastname']); 
  $firstname = addslashes($row['firstname']); 
  $playernumber = $row['playernumber'];

  if( mysqli_num_rows($result) != 0) { echo "$('#players').tokenfield('createToken', { value: '$user_key', label: '$playernumber $firstname $lastname' });"; }

}



?>
 
});

  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '400',
      width: '750',
      videoId: '<?= $youtubeID; ?>'
    });
  }

$(".timestart").on("click", function(e){
  e.preventDefault();
  $('#timestart').val(Math.round(player.getCurrentTime()));    
})

$(".timeend").on("click", function(e){
  e.preventDefault();
  $('#timeend').val(Math.round(player.getCurrentTime()));    
})

      

</script>



</div>

 

